#include "httpclient.h"
#include <QApplication>
#include <QPixmap>
#include <QSslConfiguration>
#include <QTextCodec>
#include <QTime>
#include <QSslError>
#include <QList>
#include <QBitmap>

HttpClient::HttpClient()
{
    qnam = new QNetworkAccessManager(this);
    QObject::connect(qnam,SIGNAL(finished(QNetworkReply*)),this,SLOT(OnGetFinished(QNetworkReply*)));
    QObject::connect(qnam,SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),this,SLOT(OnSslErrors(QNetworkReply*,QList<QSslError>)));
}

HttpClient::~HttpClient()
{
    delete qnam;
}

QString HttpClient::GetString(QString url)
{
    qDebug()<<"HttpClient::GetString start..."<<url;
    QString result;
    QNetworkReply *reply = qnam->get(QNetworkRequest(QUrl(url)));

    QTime time;
    time.start();

    bool timeout = false;
    while(!reply->isFinished())
    {
        if(time.elapsed() >= TIMEOUT)
        {
            timeout = true;
            break;
        }
        QApplication::processEvents();
    }
    if(!timeout && reply->error() == QNetworkReply::NoError)
    {
        QTextCodec *codec = QTextCodec::codecForName("utf8");
        result = codec->toUnicode(reply->readAll());
        qDebug()<<"response size : "<<result.size();
    }

    reply->deleteLater();
    qDebug()<<"HttpClient::GetString end..."<<url;
    return result;
}

QString HttpClient::PostString(QString url,QString data)
{
    QString result;
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    QSslConfiguration sslCon = request.sslConfiguration();
    sslCon.setPeerVerifyMode(QSslSocket::VerifyNone);
    request.setSslConfiguration(sslCon);
    request.setHeader(QNetworkRequest::ContentTypeHeader,
                      QString("application/x-www-form-urlencoded"));

    QNetworkReply *reply = qnam->post(request, data.toLatin1());
    reply->ignoreSslErrors();

    QTime _t;
    _t.start();

    bool _timeout = false;

    while (!reply->isFinished()) {
        QApplication::processEvents();
        if (_t.elapsed() >= TIMEOUT) {
            _timeout = true;
            break;
        }
    }
    if (!_timeout && reply->error() == QNetworkReply::NoError) {
        result = reply->readAll();
    }

    reply->deleteLater();

    return result;
}

QNetworkReply* HttpClient::GetByteArray(QString url)
{
    QNetworkReply *reply = qnam->get(QNetworkRequest(QUrl(url)));

    QTime time;
    time.start();

    bool timeout = false;
    while(!reply->isFinished())
    {
        QApplication::processEvents();
        if(time.elapsed() >= TIMEOUT)
        {
            timeout = true;
            break;
        }
    }
    if(!timeout && reply->error() ==QNetworkReply::NoError)
    {
        return reply;
    }
    else
    {
        qDebug()<<"HttpClient:GetByteArray Error: "<<reply->errorString();
    }
    return reply;
}

void HttpClient::GetStringAsync(QUrl url)
{
    this->currentType = Get;
    qnam->get(QNetworkRequest(url));
}

void HttpClient::GetByteArrayAsync(QUrl url)
{
    this->currentType = ByteArray;
    qnam->get(QNetworkRequest(url));
}

void HttpClient::GetImageAsync(QUrl url, QString fileName)
{
    this->currentType = Image;
    this->tag = fileName;
    qnam->get(QNetworkRequest(url));
}


QNetworkReply* HttpClient::DownloadImage(QString url,QString filename)
{
    this->currentType = Image;

    QNetworkReply* reply = GetByteArray(url);

    return reply;
}

void HttpClient::OnSslErrors(QNetworkReply *reply, QList<QSslError> errors)
{
    emit SslError(reply,errors);
}

void HttpClient::OnGetFinished(QNetworkReply *reply)
{
    switch(currentType)
    {
        case Get:
        {
            QTextCodec *codec = QTextCodec::codecForName("utf8");
            QString str = codec->toUnicode(reply->readAll());
            emit GetStringFinished(str);
            break;
        }
        case Post:
        {
            emit PostFinished(reply);
            break;
        }
        case ByteArray:
        {
            emit GetByteArrayFinished(reply);
            break;
        }
        case Image:
        {
            emit(GetImageFinished(reply,this->tag));
            break;
        }
        default:
        {
            emit HttpTypeError(this->currentType);
            qDebug()<<"Invalid Http type"<<this->currentType;
            break;
        }
    }
}
